<template>
  <div
    class="min-h-screen flex items-center justify-center bg-gradient-to-br from-blue-50 to-indigo-100"
  >
    <div class="card p-8 max-w-md w-full mx-4">
      <h1 class="text-3xl font-bold text-center text-gray-800 mb-8">
        你画我猜
      </h1>

      <div class="space-y-4">
        <button @click="createRoom" class="btn btn-primary w-full py-3 text-lg">
          创建房间
        </button>

        <div class="flex gap-2">
          <input
            v-model="roomId"
            type="text"
            placeholder="输入房间号"
            class="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500"
          />
          <button
            @click="joinRoom"
            :disabled="!roomId.trim()"
            class="btn btn-primary px-6"
          >
            加入
          </button>
        </div>

        <!-- 导航按钮 -->
        <div class="pt-4 border-t border-gray-200 space-y-2">
          <button
            @click="$router.push('/wordbanks')"
            class="btn btn-secondary w-full py-2"
          >
            词库管理
          </button>
          <button
            @click="$router.push('/settings')"
            class="btn btn-secondary w-full py-2"
          >
            游戏设置
          </button>
        </div>
      </div>

      <!-- 添加服务器状态显示 -->
      <div class="mt-6 pt-4 border-t border-gray-200">
        <div class="flex items-center justify-center gap-2 text-sm">
          <div
            class="w-2 h-2 rounded-full"
            :class="serverStatus ? 'bg-green-500' : 'bg-red-500'"
          ></div>
          <span class="text-gray-600">
            {{ serverStatus ? "服务器已连接" : "服务器连接中..." }}
          </span>
        </div>
        <div v-if="serverInfo" class="text-xs text-gray-500 text-center mt-1">
          活跃房间: {{ serverInfo.activeRooms }} | 在线玩家:
          {{ serverInfo.totalPlayers }}
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { apiService } from "../services/api";

const router = useRouter();
const roomId = ref("");
const serverStatus = ref(false);
const serverInfo = ref<any>(null);

const createRoom = () => {
  const newRoomId = Math.random().toString(36).substring(2, 8).toUpperCase();
  router.push(`/game/${newRoomId}`);
};

const joinRoom = () => {
  if (roomId.value.trim()) {
    router.push(`/game/${roomId.value.trim()}`);
  }
};

const checkServerStatus = async () => {
  try {
    serverInfo.value = await apiService.getServerStatus();
    serverStatus.value = true;
  } catch (error) {
    serverStatus.value = false;
    console.error("服务器连接失败:", error);
  }
};

onMounted(() => {
  checkServerStatus();
  // 定期检查服务器状态
  setInterval(checkServerStatus, 30000); // 每30秒检查一次
});
</script>
